package logic

import (
	"context"
	"strings"
	"time"

	"server-go/rpc/reward/internal/models"
	"server-go/rpc/reward/internal/svc"
	"server-go/rpc/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type DoRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDoRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DoRegisterLogic {
	return &DoRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册用户模块 register
func (l *DoRegisterLogic) DoRegister(in *reward.DoRegisterInput) (*reward.DoRegisterOutput, error) {
	out := &reward.DoRegisterOutput{}
	usersDao := &models.UsersDao{Email: in.Email}
	if err := usersDao.First(l.svcCtx.Db); err != nil {
		out.EmailError = true
		return out, err
	}
	if usersDao.Id != 0 {
		out.EmailError = true
		return out, nil
	}
	// 获取验证码
	captcha, err := util.RedisGet(l.svcCtx.Redis, in.Email)
	if err != nil || captcha == "" || !strings.EqualFold(captcha, in.Captcha) {
		out.CaptchaError = true
		return out, nil
	}
	// 新增用户
	userName := util.RandNum(9)
	intro := "ta是个神秘人"
	if in.Intro != "" {
		intro = in.Intro
	}
	usersDaoEnd := &models.UsersDao{
		Nickname:    in.Nickname,
		Username:    userName,
		Email:       in.Email,
		Password:    in.Password,
		Userintro:   intro,
		Gender:      in.Gender,
		Createtime:  int(time.Now().Unix()),
		Agree:       "yes",
		HeadImgPath: "/" + userName + ".jpg",
	}
	tx := l.svcCtx.Db.Begin()
	if err := usersDaoEnd.AddOne(tx); err != nil {
		tx.Rollback()
		return out, err
	}
	tx.Commit()
	out.RegisterSuccess = true
	out.Username = userName
	return out, nil
}
